package org.jeecg.modules.achachievementsubject.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.config.mybatis.TenantContext;
import org.jeecg.modules.achachievementsubject.entity.AchAchievementSubject;
import org.jeecg.modules.achachievementsubject.entity.AchAchievementSubjectDemo;
import org.jeecg.modules.achachievementsubject.mapper.AchAchievementSubjectMapper;
import org.jeecg.modules.achachievementsubject.service.IAchAchievementSubjectService;
import org.jeecg.modules.achachievementsubject.vo.AchAchievementSubjectVo;
import org.jeecg.modules.achexaminationpaper.entity.AchExaminationPaper;
import org.jeecg.modules.achexaminationpaper.service.IAchExaminationPaperService;
import org.jeecg.modules.achexaminationpaper.vo.AchExaminationPaperVo;
import org.jeecg.modules.classes.entity.CouClass;
import org.jeecg.modules.classes.service.ICouClassService;
import org.jeecg.modules.common.baseentity.BaseApiEntity;
import org.jeecg.modules.common.utils.DateUtil;
import org.jeecg.modules.grade.entity.CouGrade;
import org.jeecg.modules.grade.service.impl.CouGradeServiceImpl;
import org.jeecg.modules.relation.relclassstudent.entity.RelClassStudent;
import org.jeecg.modules.relation.relclassstudent.service.IRelClassStudentService;
import org.jeecg.modules.student.entity.StuStudent;
import org.jeecg.modules.student.entity.StuStudentDemo;
import org.jeecg.modules.student.service.IStuStudentService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.*;

/**
 * @Description: ach_achievement_subject
 * @author: baochangrong
 * @Date: 2022-03-18
 * @Version: V1.0
 */
@Service
public class AchAchievementSubjectServiceImpl extends ServiceImpl<AchAchievementSubjectMapper, AchAchievementSubject> implements IAchAchievementSubjectService {

    @Autowired
    AchAchievementSubjectMapper achAchievementSubjectMapper;
    @Value("${jeecg.path.upload}")
    private String upLoadPath;
    @Autowired
    private ICouClassService couClassServiceImpl;
    @Autowired
    private IRelClassStudentService relClassStudentServiceImpl;
    @Autowired
    private IAchExaminationPaperService achExaminationPaperServiceImpl;

    /**
     * 科目成绩查询 分页
     */
    @Override
    public IPage<AchAchievementSubjectVo> voList(Page<AchAchievementSubjectVo> page, AchAchievementSubjectVo achAchievementSubjectVo) {
        List<AchAchievementSubjectVo> achAchievementSubjectVoList = achAchievementSubjectMapper.voList(page, achAchievementSubjectVo);
        return page.setRecords(achAchievementSubjectVoList);
    }


    public Result<List<Map>> listBatchNumber(AchAchievementSubjectVo achAchievementSubjectVo) {
        List<Map> achAchievementSubjectList = achAchievementSubjectMapper.listBatchNumber(achAchievementSubjectVo);
        return Result.OK(achAchievementSubjectList);
    }

    /**
     * 导出excel
     *
     * @param request
     */
    public ModelAndView exportXlsDemo(HttpServletRequest request, AchAchievementSubjectDemo object, String title, String secondTitle, ISysBaseAPI sysBaseAPI, JSONObject DictList) {
        // Step.1 组装查询条件
        //LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        StringBuffer text = new StringBuffer();
        //年级、考试ID 接口比传，否则返回报错
        if (null == object.getGradeId() || "".equals(object.getGradeId()) || null == object.getExaminationId() || "".equals(object.getExaminationId())) {
            new IllegalArgumentException("请最少选择一个年级和考试名称！");
            // Step.3  正文
            ExportParams exportParams = new ExportParams(title + "模板", "请最少选择一个年级和考试名称！", title);
            exportParams.setType(ExcelType.XSSF);
            exportParams.setImageBasePath(upLoadPath);
            exportParams.setSecondTitleHeight(new Short("10"));
            //map.put("title",exportParams);//表格Title
            ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
            mv.addObject(NormalExcelConstants.PARAMS, exportParams);//表格Title
            return mv;
        }
        //处理年级、考试等批量数据处理
        List<AchAchievementSubjectDemo> achAchievementSubjectDemosList = achAchievementSubjectMapper.queryCLassExamData(object);
        // Step.3 说明部分
        DictList.forEach((key, value) -> {
            text.append(key + ": ");
            List<DictModel> dictModelList = sysBaseAPI.getDictItems(value.toString());
            for (DictModel dictModel : dictModelList) {
                text.append(dictModel.getText() + ":" + dictModel.getValue() + ";");

            }
            text.append("\n");
        });
        String secondTitleNew = secondTitle + "\n" + text.toString();

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        // Step.3  正文
        ExportParams exportParams = new ExportParams(title + "模板", secondTitleNew, title);
        exportParams.setType(ExcelType.XSSF);
        exportParams.setImageBasePath(upLoadPath);
        exportParams.setSecondTitleHeight(new Short("10"));
        //map.put("title",exportParams);//表格Title
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);//表格Title
        mv.addObject(NormalExcelConstants.CLASS, AchAchievementSubjectDemo.class);//表格对应实体
        mv.addObject(NormalExcelConstants.DATA_LIST, achAchievementSubjectDemosList);//数据集合
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @Transactional
    public Result<?> importExcelDemo(HttpServletRequest request, HttpServletResponse response, IAchAchievementSubjectService achAchievementSubjectService, BaseApiEntity baseApiEntity) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            String batchNumber = baseApiEntity.getUsername() + DateUtil.getNow("yyyyMMddHHmm");
            long start = System.currentTimeMillis();
            try {
                List<AchAchievementSubject> list = ExcelImportUtil.importExcel(file.getInputStream(), AchAchievementSubject.class, params);
                //update-begin-author:taoyan date:20190528 for:批量插入数据
                for (AchAchievementSubject st : list) {
                    st.setSysOrgCode(baseApiEntity.getSysOrgCode());
                    st.setBatchNumber(batchNumber);
                    st.setCreateTime(DateUtil.getCurrentDate());
                    st.setTenantId(TenantContext.getTenant());
                    st.setCreateBy(baseApiEntity.getUsername());
                    if ("".equals(st.getAchievementScore()) || null == st.getAchievementDate()) {
                        new IllegalArgumentException("文件中必填项有未填写的。" + st.toString() + "导入失败！请检查数据。");
                        return Result.error("文件中必填项有未填写的。" + st.toString() + "导入失败！请检查数据。");
                    }
                }
                achAchievementSubjectService.saveBatch(list);
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
                log.debug("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

}
